package com.hzncc.flowable_diboot.controller.customer;

import com.diboot.core.binding.Binder;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.JSON;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.dto.SalesTeamDTO;
import com.hzncc.flowable_diboot.entity.Customer;
import com.hzncc.flowable_diboot.entity.SalesTeam;
import com.hzncc.flowable_diboot.service.CustomerService;
import com.hzncc.flowable_diboot.service.SalesTeamService;
import com.hzncc.flowable_diboot.vo.SalesTeamDetailVO;
import com.hzncc.flowable_diboot.vo.SalesTeamListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* 销售团队 相关rest接口
* @author MyName
* @version 1.0
* @date 2024-05-21
* Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/sales-team")
@BindPermission(name = "销售团队")
@RestController
public class SalesTeamController extends BaseCrudRestController<SalesTeam> {

    @Autowired
    private SalesTeamService salesTeamService;
    @Autowired
    private CustomerService customerService;

    /**
    * 查询资源对象的列表VO记录
    * <p>
    * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
    * </p>
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<SalesTeamListVO>> getListVOMapping(SalesTeamDTO queryDto, Pagination pagination) throws Exception {
        JsonResult<List<SalesTeamListVO>> result = super.getViewObjectList(queryDto, pagination, SalesTeamListVO.class);
        List<SalesTeamListVO> voList = result.getData();
        Binder.bindRelations(voList);
        return result;
    }

    /**
    * 根据id查询资源对象的详情VO
    * @param id ID
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<SalesTeamDetailVO> getDetailVOMapping(@PathVariable("id")String id) throws Exception {
        SalesTeamDetailVO detailVO = salesTeamService.getViewObject(id, SalesTeamDetailVO.class);
        return JsonResult.OK(detailVO);
    }


    /**
    * 创建资源对象数据
    * @param salesTeam
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody SalesTeam salesTeam) throws Exception {
        Customer customer = customerService.getEntity(salesTeam.getCustomerId());
        if (!S.equals(customer.getPrincipal(), IamSecurityUtils.getCurrentUserId())){
            return JsonResult.FAIL_NO_PERMISSION("权限不足，请联系客户负责人");
        }
        // 添加多个成员
        String memberStr = salesTeam.getMember();
        List<String> memberIds = JSON.parseArray(memberStr, String.class);
        memberIds = memberIds.stream().distinct().collect(Collectors.toList());
        List<SalesTeam> existMember = salesTeamService.getEntityList(QueryBuilder.toQueryWrapper(new SalesTeamDTO().setCustomerId(salesTeam.getCustomerId())));
        List<String> finalMemberIds = memberIds;
        List<SalesTeam> collect = existMember.stream().filter(e -> finalMemberIds.contains(e.getMember())).collect(Collectors.toList());
        if (!collect.isEmpty()){
            return JsonResult.FAIL_INVALID_PARAM("团队成员重复,请检查!");
        }
        List<SalesTeam> salesTeams = new ArrayList<>();
        for (String memberId : memberIds) {
            SalesTeam st = new SalesTeam();
            BeanUtils.copyProperties(salesTeam,st);
            st.setMember(memberId);
            //设置权限
            st.setPermissions(Objects.equals(st.getRole(),"admin")?"3":"6");
            salesTeams.add(st);
        }
        boolean success = salesTeamService.createEntities(salesTeams);
        log.debug("新建数据 销售团队:{} {}", salesTeam.getId(), success? "成功":"失败");
        return JsonResult.OK(salesTeam.getId());
    }

    /**
    * 批量创建资源对象数据
    * @param salesTeamList
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<SalesTeam> salesTeamList) throws Exception {
        boolean success = salesTeamService.createEntities(salesTeamList);
        log.debug("批量新建数据 销售团队 {}", success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
    * 根据id更新资源对象
    * @param salesTeam
    * @return JsonResult
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id")String id, @RequestBody SalesTeam salesTeam) throws Exception {
        boolean success = salesTeamService.updateEntity(salesTeam);
        log.debug("更新数据 销售团队:{} {}", id, success? "成功":"失败");
        return JsonResult.OK(success);
    }

    /**
    * 根据id删除资源对象
    * @param id
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        //boolean success = salesTeamService.deleteEntity(id);
        //log.debug("删除数据 销售团队:{} {}", id, success? "成功":"失败");
        //return JsonResult.OK(success);
        return salesTeamService.kickTheTeam(id);
    }

    /**
    * 根据ids集合删除资源对象
    * @param ids
    * @return
    * @throws Exception
    */
    @Log(operation = OperationCons.LABEL_BATCH_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = salesTeamService.deleteEntities(ids);
        log.debug("批量删除数据 销售团队:{} {}", ids, success? "成功":"失败");
        return JsonResult.OK(success);
    }
    
}